package com.liannong.service;

import com.liannong.entity.Product;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import java.util.Map;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class BlockchainService {
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private BlockchainStorageService blockchainStorageService;
    
    private static final String BLOCKCHAIN_API_URL = "http://localhost:5002"; // 区块链API地址
    
    /**
     * 创建质量记录
     * @param product 商品信息
     * @return 是否成功
     */
    public boolean createQualityRecord(Product product) {
        try {
            // 获取当前活跃区块组ID
            String activeGroupId = blockchainStorageService.getCurrentActiveGroupId();
            
            // 模拟API调用，不实际调用
            log.info("创建区块链质量记录(模拟) - traceCode: {}, groupId: {}", product.getTraceCode(), activeGroupId);
            
            /* 注释实际API调用
            // 构建请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("traceCode", product.getTraceCode());
            params.put("minTemp", product.getMinTemp() != null ? product.getMinTemp() : 0);
            params.put("maxTemp", product.getMaxTemp() != null ? product.getMaxTemp() : 0);
            params.put("groupId", activeGroupId); // 添加区块组ID
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            // 创建请求实体
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(
                BLOCKCHAIN_API_URL + "/createQualityRecord",
                request,
                String.class
            );
            
            // 检查响应
            if (response.getStatusCode().is2xxSuccessful()) {
                log.info("区块链质量记录创建成功 - traceCode: {}, groupId: {}", product.getTraceCode(), activeGroupId);
                
                // 交易完成后，检查是否需要切换区块组
                blockchainStorageService.switchBlockGroupIfNeeded();
                
                return true;
            } else {
                log.error("区块链质量记录创建失败 - traceCode: {}, status: {}", 
                    product.getTraceCode(), response.getStatusCode());
                return false;
            }
            */
            
            // 直接返回成功，模拟创建成功
            // 交易完成后，检查是否需要切换区块组
            blockchainStorageService.switchBlockGroupIfNeeded();
            return true;
        } catch (Exception e) {
            log.error("区块链质量记录创建异常", e);
            return false;
        }
    }

    /**
     * 提交温度记录
     * @param traceCode 溯源码
     * @param temperature 温度
     * @return 是否成功
     */
    public boolean submitTemperatureRecord(String traceCode, int temperature) {
        try {
            // 获取当前活跃区块组ID
            String activeGroupId = blockchainStorageService.getCurrentActiveGroupId();
            
            // 模拟API调用，不实际调用
            log.info("提交温度记录(模拟) - traceCode: {}, temperature: {}, groupId: {}", 
                     traceCode, temperature, activeGroupId);
            
            /* 注释实际API调用
            // 构建请求参数
            Map<String, Object> params = new HashMap<>();
            params.put("traceCode", traceCode);
            params.put("temperature", temperature);
            params.put("timestamp", System.currentTimeMillis() / 1000); // 转换为秒
            params.put("groupId", activeGroupId); // 添加区块组ID
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            // 创建请求实体
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, headers);
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(
                BLOCKCHAIN_API_URL + "/submitTemperatureRecord",
                request,
                String.class
            );
            
            // 检查响应
            if (response.getStatusCode().is2xxSuccessful()) {
                log.info("温度记录提交成功 - traceCode: {}, temperature: {}, groupId: {}", 
                         traceCode, temperature, activeGroupId);
                
                // 交易完成后，检查是否需要切换区块组
                blockchainStorageService.switchBlockGroupIfNeeded();
                
                return true;
            } else {
                log.error("温度记录提交失败 - traceCode: {}, status: {}", traceCode, response.getStatusCode());
                return false;
            }
            */
            
            // 直接返回成功，模拟提交成功
            // 交易完成后，检查是否需要切换区块组
            blockchainStorageService.switchBlockGroupIfNeeded();
            return true;
        } catch (Exception e) {
            log.error("温度记录提交异常", e);
            return false;
        }
    }

    /**
     * 检查质量状态
     * @param traceCode 溯源码
     * @return 质量状态信息
     */
    public Map<String, Object> checkQualityStatus(String traceCode) {
        try {
            // 模拟API调用，不实际调用
            log.info("检查质量状态(模拟) - traceCode: {}", traceCode);
            
            /* 注释实际API调用
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            // 构建请求参数，包含所有可能的区块组ID，以便在所有组中搜索
            StringBuilder url = new StringBuilder(BLOCKCHAIN_API_URL + "/checkQualityStatus/" + traceCode);
            url.append("?activeGroupId=").append(blockchainStorageService.getCurrentActiveGroupId());
            
            // 发送请求
            ResponseEntity<Map> response = restTemplate.getForEntity(
                url.toString(),
                Map.class
            );
            
            // 检查响应
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                log.info("质量状态查询成功 - traceCode: {}", traceCode);
                return response.getBody();
            } else {
                log.error("质量状态查询失败 - traceCode: {}, status: {}", 
                    traceCode, response.getStatusCode());
                return null;
            }
            */
            
            // 返回模拟数据
            Map<String, Object> result = new HashMap<>();
            result.put("traceCode", traceCode);
            result.put("status", "正常");
            result.put("minTemp", 2);
            result.put("maxTemp", 8);
            result.put("currentTemp", 5);
            result.put("lastUpdate", System.currentTimeMillis());
            result.put("qualityScore", 95);
            result.put("groupId", blockchainStorageService.getCurrentActiveGroupId());
            
            return result;
        } catch (Exception e) {
            log.error("质量状态查询异常", e);
            return null;
        }
    }
} 